// pages/assess/assess.js
import { Toast, ajax } from '../../utils/index'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    active: 0,
    answer: '我们为什么要做120平的产品？',
    dataList: [],
    questionList: [],
    assessResult: null,
    startDate: new Date(),
    endDate: null,
    start_end_timer: null,
    timer: null,
    status: false,
    overlay_show: false
  },
  // 下一题按钮事件
  nextClick() {
    let { dataList, active } = this.data
    // if (!dataList[active].voiceKey) return Toast('请完成本题作答')
    if (active + 1 == dataList.length) {
      return this.setData({
        overlay_show: true,
        endDate: new Date()
      })
    }
    this.setData({
      active: active + 1
    }), this.timing()
  },
  addAuestion() {
    let { questionList, dataList, active } = this.data
    questionList.push({
      questionId: dataList[active].questionId, //	问题ID
      voiceUrl: '', //语音URL	
      qxdPoint: 0, //清晰度得分
      ylPoint: 0, //音量得分	
      lldPoint: 0, //流利度得分	
      zqlPoint: 0, //准确度得分	
      ysPoint: 0, //语速得分	
    })
    this.setData({
      questionList: questionList
    })
  },
  timing() {
    let { timer } = this.data
    timer = setInterval(() => {
      let { dataList, active, status } = this.data
      if (dataList[active].time-- <= 0 || status) {
        dataList.length != active + 1 ? (this.setData({
          active: active + 1
        }), this.timing(), this.addAuestion()) : (this.addAuestion(), this.setData({
          overlay_show: true,
          endDate: new Date()
        }));
        return clearInterval(timer)
      }
      this.setData({
        dataList: dataList
      })
      console.log(dataList[active].time)
    }, 1000)
    this.setData({
      timer: timer
    })
  },
  // 取消题目开始答题倒计时
  cancelTime() {
    let { timer } = this.data
    clearInterval(timer)
  },
  // tab变化事件
  tabChange(e) {
    console.log('tab变化事件', e)
    if (e.type === "change") {
      this.setData({
        active: e.detail.index
      })
    }
  },

  // 录音事件
  recordChange(e) {
    console.log('录音事件==============', e)
    let { score, audioUrl } = e.detail, { active, dataList, questionList } = this.data
    wx.downloadFile({
      url: audioUrl,
      success: (res) => {
        if (res.statusCode === 200) {
          dataList[active].voiceKey = res.tempFilePath
          this.setData({
            dataList: dataList
          })
        }
      }
    })
    dataList[active].point = score.synthesizeScore.toFixed(2)
    score.questionId = dataList[active].questionId
    score.voiceUrl = audioUrl
    questionList.push(score)
    this.setData({
      dataList: dataList,
      questionList: questionList,
      default: true
    })
    console.log(this.data.dataList, this.data.questionList)
  },
  // 初始化事件
  infoChange() {
    this.questionsList()
    this.setData({
      active: 0,
      questionList: [],
      overlay_show: false
    })
  },
  // 提交事件
  submit() {
    this.setData({
      overlay_show: false
    })
    let {assessResult,questionList,startDate,endDate } = this.data,time = [endDate.getHours() - startDate.getHours(), endDate.getMinutes() - startDate.getMinutes() , endDate.getSeconds() - startDate.getSeconds()],entity = {
      assessId: assessResult.assessId,
      questionList: questionList,
      useTime: time.join(':')
    };
    this.submitRequest(entity)
  },
  submitRequest(e) {
    ajax.loading()
    return new Promise((resolve, reject) => {
      ajax.post('/applet/assess/submitAssess', e).then(res => {
        if (res.data.code == 1) {
          Toast({
            type: 'success',
            message: '提交成功',
            forbidClick: true,
            onClose: () => wx.navigateBack()
          }),resolve(res)
        } else ajax.toast.fail(res.data.msg), reject(res)
      }).catch(e => (ajax.toast.fail('接口错误'), reject(e), console.log(e, '提交考核')))
    })
  },
  // 考核结果列表查询 || 题目列表
  questionsList(e) {
    ajax.loading()
    return new Promise((resolve, reject) => {
      ajax.post('/applet/assess/queryAssessResult', {
        assessId: e.id - 0
      }).then(res => {
        if (res.data.code == 1) {
          let { assessQuestionList,assessResult } = res.data.data
          assessQuestionList.forEach((item, index) => {
            let num = item.content.length// * (index + 1)
            item.time = num < 20 ? 5 : num < 40 ? 10 : num < 60 ? 15 : 25
          })
          console.log(assessQuestionList)
          this.setData({
            startDate: new Date(),
            dataList: assessQuestionList,
            assessResult: assessResult
          }), this.timing()
            , ajax.toast.clear(), resolve(res)
        } else ajax.toast.fail(res.data.msg), reject(res)
      }).catch(e => (ajax.toast.fail('接口错误'), reject(e), console.log(e, '考核结果列表查询')))
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.questionsList(options)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})